//
//  ComposeViewController.swift
//  Weibo
//
//  Created by 付启刚 on 15/12/26.
//  Copyright © 2015年 faq. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
class ComposeViewController: UIViewController {
 @objc private func close(){
    dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func send(){
    let urlString="2/statuses/update.json"
        guard let token = UserAccountViewModel().token else{
        SVProgressHUD.showInfoWithStatus("请重新登录",maskType: .Gradient)
            return
        }
        let parameter=["access_token": token,"status": textView.text ?? ""]
        NetWorkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: parameter) { (dict, error) -> () in
            if error != nil {
            SVProgressHUD.showInfoWithStatus("发布微博失败,请检查网络", maskType: .Gradient)
                return
            }
            SVProgressHUD.showSuccessWithStatus("发布微博成功", maskType: .Gradient)
            self.dismissViewControllerAnimated(true, completion: nil)

        }
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
       textView.becomeFirstResponder()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
       
    }
    
    private func registerNotification() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    @objc private func keyBoardWillChange(n:NSNotification) {
        //获取通知中的内容
        print(n)
        //获取键盘弹出改变的时间
    let duraton=(n.userInfo![UIKeyboardAnimationDurationUserInfoKey]as!NSNumber).doubleValue
        //获取键盘弹出改变的Frame值
    let endRect=(n.userInfo![UIKeyboardFrameEndUserInfoKey]as!NSValue).CGRectValue()
        print(duraton,endRect)
        //获取键盘弹出与初始状态的偏移量Y值
        let offsetY = -screenH + endRect.origin.y
       //刷新toolBar的位置和约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offsetY)
        }
        UIView.animateWithDuration(duraton) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
   
    func setupUI(){
       //设置背景色
        view.backgroundColor=UIColor.whiteColor()
        setTextView()
        setNavBar()
        setToolBar()
        registerNotification()
    }
    private func setToolBar() {
    //给toolBar设置 items数组
        var items=[UIBarButtonItem]()
        //向数组中添加元素
        let itemSettings=[["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName":"selectEmoticonKeyboard"],
            ["imageName": "compose_add_background"]]
        //遍历配置的数组
        for item in itemSettings {
        let imageName=item["imageName"]
            let itemBtn=UIButton(imageName: nil, backImageName: imageName!)
            if let action = item["actionName"] {
                itemBtn.addTarget(self,action:Selector(action),forControlEvents: .TouchUpInside)
                
            }
            let barButtonItem = UIBarButtonItem(customView: itemBtn)
            //添加到数组中
            items.append(barButtonItem)
            //添加弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        //移除最后一个弹簧
        items.removeLast()
        toolBar.items=items
        //添加到父视图
        view.addSubview(toolBar)
        //添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
        }
        
    }
    private func setTextView() {
        //添加子控件
        view.addSubview(textView)
        //设置约束
    textView.snp_makeConstraints { (make) -> Void in
        make.left.right.top.equalTo(self.view)
        make.height.equalTo(screenH/3)
        }
        //给textView添加文本
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    //设置导航条
    private func setNavBar() {
        //左边按钮
        self.navigationItem.leftBarButtonItem=UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        //右边按钮
        self.navigationItem.rightBarButtonItem=UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        //默认右边发送按钮不交互
        self.navigationItem.rightBarButtonItem?.enabled = false
        //导航条标题
        let titleView=UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView=titleView
        let titleLabel=UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 17)
        let  nameLabel=UILabel(title: UserAccountViewModel().userName ?? "", color: UIColor.lightGrayColor(), fontSize: 14)
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        //设置约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
    private lazy var textView:UITextView = {
        let tv=UITextView()
        tv.backgroundColor=UIColor.radomColor()
        tv.font = UIFont.systemFontOfSize(18)
        tv.alwaysBounceVertical=true
        tv.keyboardDismissMode = .OnDrag
        tv.delegate=self
        return tv
    }()
    private lazy var placeHolderLabel:UILabel = UILabel(title: "请输入新鲜事", color: UIColor.lightGrayColor(), fontSize: 18)
    private lazy var toolBar:UIToolbar=UIToolbar()
    //析构函数 移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
extension ComposeViewController:UITextViewDelegate{
    //实时监测文本的变化
    func textViewDidChange(textView:UITextView){
        placeHolderLabel.hidden=textView.hasText()
        self.navigationItem.rightBarButtonItem?.enabled=textView.hasText()
    }
}

